/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package libraryproject;

import database_objects.Book;
import database_objects.Department;
import java.sql.SQLException;
import java.util.ArrayList;
import javax.swing.JDialog;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.table.DefaultTableModel;
import user_client.LibrarianUserClient;

/**
 *
 * @author pawel
 */
public class DepartmentChoicePane extends javax.swing.JPanel {

    /**
     * Creates new form DepartmentChoicePane
     */
    public DepartmentChoicePane() {
        initComponents();
        this.model = (DefaultTableModel) resultTable.getModel();
        this.resultTable.getSelectionModel().addListSelectionListener(
				new MySelectionListener());
    }

    public DepartmentChoicePane(LibrarianUserClient client, Book currentBook,
            BooksManagementsPane booksManagementsPane, JDialog owner) {
        initComponents();
        this.client = client;
        System.out.println(this.client);
        this.model = (DefaultTableModel) resultTable.getModel();
        this.currentBook = currentBook;
        this.resultTable.getSelectionModel().addListSelectionListener(
				new MySelectionListener());
        this.booksManagementsPane = booksManagementsPane;
        this.owner = owner;
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        searchButton = new javax.swing.JButton();
        addButton = new javax.swing.JButton();
        removeButton = new javax.swing.JButton();
        jPanel3 = new javax.swing.JPanel();
        jLabel4 = new javax.swing.JLabel();
        caseNumberField = new javax.swing.JTextField();
        jLabel2 = new javax.swing.JLabel();
        nameField = new javax.swing.JTextField();
        jButton2 = new javax.swing.JButton();
        labelResult = new javax.swing.JLabel();
        jScrollPane1 = new javax.swing.JScrollPane();
        resultTable = new javax.swing.JTable();

        searchButton.setText("szukaj");
        searchButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                searchButtonActionPerformed(evt);
            }
        });

        addButton.setText("dodaj");
        addButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                addButtonActionPerformed(evt);
            }
        });

        removeButton.setText("usuń");
        removeButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                removeButtonActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(searchButton, javax.swing.GroupLayout.DEFAULT_SIZE, 133, Short.MAX_VALUE)
                    .addComponent(addButton, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(removeButton, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addComponent(searchButton)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(addButton)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(removeButton))
        );

        jLabel4.setText("nazwa działu:");

        caseNumberField.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                caseNumberFieldActionPerformed(evt);
            }
        });

        jLabel2.setText("numer regału:");

        nameField.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                nameFieldActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3);
        jPanel3.setLayout(jPanel3Layout);
        jPanel3Layout.setHorizontalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel3Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel3Layout.createSequentialGroup()
                        .addComponent(jLabel4)
                        .addGap(0, 0, Short.MAX_VALUE))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel3Layout.createSequentialGroup()
                        .addGap(0, 0, Short.MAX_VALUE)
                        .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(caseNumberField, javax.swing.GroupLayout.PREFERRED_SIZE, 130, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(nameField, javax.swing.GroupLayout.PREFERRED_SIZE, 130, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jLabel2))))
                .addContainerGap())
        );
        jPanel3Layout.setVerticalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel3Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel4, javax.swing.GroupLayout.PREFERRED_SIZE, 17, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(nameField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jLabel2)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(caseNumberField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(75, Short.MAX_VALUE))
        );

        jButton2.setText("zatwierdź wybór");
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });

        labelResult.setText("Nie wybrano żadnego działu.");

        resultTable.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null},
                {null, null, null},
                {null, null, null},
                {null, null, null}
            },
            new String [] {
                "id działu", "nazwa działu", "nr regału"
            }
        ) {
            boolean[] canEdit = new boolean [] {
                false, false, false
            };

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        jScrollPane1.setViewportView(resultTable);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jPanel3, javax.swing.GroupLayout.PREFERRED_SIZE, 145, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(0, 12, Short.MAX_VALUE)
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 452, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(layout.createSequentialGroup()
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 18, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(labelResult, javax.swing.GroupLayout.PREFERRED_SIZE, 422, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(0, 0, Short.MAX_VALUE))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(jButton2, javax.swing.GroupLayout.PREFERRED_SIZE, 214, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jPanel3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 243, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(labelResult, javax.swing.GroupLayout.PREFERRED_SIZE, 22, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jButton2)))
                .addContainerGap(399, Short.MAX_VALUE))
        );
    }// </editor-fold>//GEN-END:initComponents

    private void searchButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_searchButtonActionPerformed
        try {
             System.out.println(client);
            ArrayList<Department> departments = client.searchDepartments(
                    nameField.getText(), caseNumberField.getText());

            while (model.getRowCount() > 0) {
                try {
                    model.removeRow(0);
                } catch (Exception a) {
                    System.out.println("ERRRORRRRRRRR????");
                }

            }

            for (Department dep : departments) {
                System.out.println(dep.getName());
                String[] val = new String[3];
                val[0] = dep.getId();
                val[1] = dep.getName();
                val[2] = dep.getBookCaseNumber();
                model.addRow(val);
            }

            resultTable.revalidate();
            resultTable.repaint();

        } catch (SQLException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }     // TODO add your handling code here:
    }//GEN-LAST:event_searchButtonActionPerformed

    private void addButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_addButtonActionPerformed
        String name = nameField.getText();
        // String numberOfPane = dataPane.
        String numberOfCaseLocal = caseNumberField.getText();

        if ((name.length() > 0) && (name != "")
                && (numberOfCaseLocal != "")
                && (numberOfCaseLocal.length() > 0)) {

            try {
                Integer index = client.addDepartment(name,
                        numberOfCaseLocal);
                if (index != -1) {
                    System.out.println("INDEX:" + index);
                    String[] newRow = new String[3];
                    newRow[0] = index.toString();
                    newRow[1] = name;
                    newRow[2] = numberOfCaseLocal;
                    model.addRow(newRow);
                    model.fireTableDataChanged();
                    resultTable.revalidate();
                    resultTable.repaint();

                    labelResult.setText("Dodano element");
                } else {
                    labelResult.setText("Podany dział już istnieje");
                }
            } catch (SQLException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            }

        }
        // TODO add your handling code here:
    }//GEN-LAST:event_addButtonActionPerformed

    private void removeButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_removeButtonActionPerformed
        try {
            if (idOfDepartmentTemp != null) {
                client.removeElement(idOfDepartmentTemp.toString(), "dzialy",
                        "id_dzialu");
                System.out.println("usunięto element.");
            }
            int i = 0;
            // Integer size =
            // DepartmentManagerPane.this.model.getRowCount();

            while (i < model.getRowCount()) {
                Integer valS = Integer.valueOf((String) resultTable.getValueAt(
                        i, 0));

                if (Integer.valueOf(valS) == idOfDepartmentTemp) {
                    model.removeRow(i);
                    model.fireTableDataChanged();

                }

                // DepartmentManagerPane.this.model.removeRow(0);
                i++;
            }
            resultTable.setModel(model);
            resultTable.revalidate();
            resultTable.repaint();

        } catch (SQLException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }

    }//GEN-LAST:event_removeButtonActionPerformed

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed

        name = nameTemp;
        idOfDepartment = idOfDepartmentTemp;
        bookCaseNumber = bookCaseNumberTemp;
        
        Department department = new Department(name, idOfDepartment.toString(),
                bookCaseNumber.toString());
        booksManagementsPane.setDepartment(department);
        
        if (owner!= null) {
            owner.dispose();
        }
        // TODO add your handling code here:
    }//GEN-LAST:event_jButton2ActionPerformed

    private void nameFieldActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_nameFieldActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_nameFieldActionPerformed

    private void caseNumberFieldActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_caseNumberFieldActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_caseNumberFieldActionPerformed

    private class MySelectionListener implements ListSelectionListener {

        @Override
        public void valueChanged(ListSelectionEvent e) {
            // TODO Auto-generated method stub
            try {
                System.out.println("SELECTION LISTENER");
                String idString = (String) model.getValueAt(
                        resultTable.getSelectedRow(), 0);
                idOfDepartmentTemp = Integer.valueOf(idString);
                nameTemp = (String) model.getValueAt(resultTable.getSelectedRow(),
                        1);
                String bookCase = (String) model.getValueAt(
                        resultTable.getSelectedRow(), 2);
                bookCaseNumberTemp = Integer.valueOf(bookCase);
                System.out.println(idOfDepartmentTemp + ", " + nameTemp + ", "
                        + bookCaseNumberTemp);

                labelResult.setText(idOfDepartmentTemp + " " + nameTemp + " "
                        + bookCaseNumberTemp);

            } catch (ArrayIndexOutOfBoundsException e1) {
                labelResult.setText("nie wybrano działu");
                idOfDepartment = null;
                name = null;
                bookCaseNumber = null;

            }
        }
    }
    
    private Book currentBook = null;
    private LibrarianUserClient client = null;
    private DefaultTableModel model = null;
    private Integer idOfDepartment = null;
    private String name = "";
    private Integer bookCaseNumber = null;
    private Integer idOfDepartmentTemp = null;
    private String nameTemp = "";
    private Integer bookCaseNumberTemp = null;
    private JDialog owner = null;
    private BooksManagementsPane booksManagementsPane = null;
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton addButton;
    private javax.swing.JTextField caseNumberField;
    private javax.swing.JButton jButton2;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel3;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JLabel labelResult;
    private javax.swing.JTextField nameField;
    private javax.swing.JButton removeButton;
    private javax.swing.JTable resultTable;
    private javax.swing.JButton searchButton;
    // End of variables declaration//GEN-END:variables
}
